package com.chat.ui.slideshow;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;

import com.chat.R;
import com.chat.entity.DataPackage;
import com.chat.entity.ServerAction;
import com.chat.entity.User;
import com.chat.entity.event.ChannelEvent;
import com.chat.net.SocketClient;
import com.chat.net.socket.Channel;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;



/**
 * 个人信息页面
 *
 */
public class SlideshowFragment extends Fragment {
    final int RESULT_OK = -1;
    private SlideshowViewModel slideshowViewModel;
    ImageView head;
    User user;
    TextView name;
    byte[] headImg = null;

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == 200){
                if(headImg!=null) {
                    Drawable image = new BitmapDrawable(getResources(), BitmapFactory.decodeByteArray(headImg, 0, headImg.length));
                    head.setBackground(image);
                    name.setText(user.getName());
                }
            }
        }
    };



    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        slideshowViewModel =
                ViewModelProviders.of(this).get(SlideshowViewModel.class);
        View root = inflater.inflate(R.layout.fragment_slideshow, container, false);
        head = root.findViewById(R.id.personal_head);
        name = root.findViewById(R.id.personal_name);
        head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openGallery();
            }
        });
        getUserInfo();

        return root;
    }

    public void openGallery() {
        CropImage.activity()
                .setGuidelines(CropImageView.Guidelines.ON)
                .start(getContext(),this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {

        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if (resultCode == RESULT_OK) {
                Uri resultUri = result.getUri();
                try {
                    uploadHead(resultUri);
                } catch (IOException e) {
                    Log.e("com.chat",e.toString());
                    e.printStackTrace();
                }


            } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                Exception error = result.getError();
            }
        }


    }

    public void uploadHead(Uri uri) throws IOException {

        //上传照片
        String path = uri.getPath();
        File file = new File(path);
        Map<String,Object> params = new HashMap();
        byte[] fileBytes = new byte[(int) file.length()];
        FileInputStream fis = new FileInputStream(file);
        fis.read(fileBytes);
        fis.close();
        params.put("fileName",file.getName());
        params.put("fileContent",fileBytes);
        headImg = fileBytes;
        params.put("roomId",-1);
        SocketClient.getSocketClient().addChannelEvent(new ChannelEvent() {
            public void onChannelEvent(Channel ctx, DataPackage source) {

            }
        },DataPackage.request(params, ServerAction.SEND_FILE_FROM_ROOM));

        //更新头像
        Map<String,Object> params1 = new HashMap<>();
        params1.put("fileName",file.getName());
        params1.put("fileId",-1);
        SocketClient.getSocketClient().addChannelEvent(new ChannelEvent() {
            @Override
            public void onChannelEvent(com.chat.net.socket.Channel ctx, DataPackage source) {
                super.onChannelEvent(ctx, source);
                Message message = Message.obtain();
                message.what = source.getCode();
                handler.sendMessage(message);
            }
        },DataPackage.request(params1, ServerAction.UPDATE_USER_INFO));
    }

    public void getUserInfo(){
        //获取用户信息
        SocketClient.getSocketClient().addChannelEvent(new ChannelEvent() {
            @Override
            public void onChannelEvent(Channel ctx, DataPackage source) {
                super.onChannelEvent(ctx, source);
                if(source.getCode()==200){
                    user = (User) source.getDate();
                    Map<String,Object> params = new HashMap();
                    params.put("fileId",user.getFileId());
                    if(user.getFileId()!=-1){
                        SocketClient.getSocketClient().addChannelEvent(new ChannelEvent() {
                            @Override
                            public synchronized void onChannelEvent(Channel ctx, DataPackage source) {
                                super.onChannelEvent(ctx, source);
                                if(source.getCode()==200){
                                    headImg = (byte[]) source.getDate();
                                    Message message = Message.obtain();
                                    message.what = source.getCode();
                                    handler.sendMessage(message);
                                }
                            }
                        },DataPackage.request(params,ServerAction.DOWNLOAD_FILE_FROM_ROOM));
                    }
                }
            }
        },DataPackage.request(ServerAction.GET_USER));



    }

}
